<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateSellIssuesAPIRequest;
use App\Http\Requests\API\UpdateSellIssuesAPIRequest;
use App\Models\CarAuth;
use App\Models\CarAuthLog;
use App\Models\SellIssues;
use App\Repositories\SellIssuesRepository;
use App\Services\AuthServices;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;
use Storage;
use Excel;
use App\Models\Store;

/**
 * Class SellIssuesController
 * @package App\Http\Controllers\API
 */

class SellIssuesAPIController extends AppBaseController
{
    /** @var  SellIssuesRepository */
    private $sellIssuesRepository;
    use AuthServices;

    public function __construct(SellIssuesRepository $sellIssuesRepo)
    {
        $this->sellIssuesRepository = $sellIssuesRepo;
    }

    /**
     * Display a listing of the SellIssues.
     * GET|HEAD /sellIssues
     *
     * @param Request $request
     * @return Response
     */
    public function index(Request $request)
    {
        $park_arr = $this->getUserParks();
        $this->sellIssuesRepository->pushCriteria(new RequestCriteria($request));
        $this->sellIssuesRepository->pushCriteria(new LimitOffsetCriteria($request));
        $sellIssues = $this->sellIssuesRepository->paginate($request->limit);
        $res = $sellIssues->toArray();
        foreach ($res['data'] as &$v) {
            $v['store_name'] = Store::where("id",$v['store_id'])->value("store_name");
            $park_list = explode(",",$v['park_code']);
            $pk = [];
            foreach ($park_list as $val) {
                $pk[] = $park_arr[$val]??'';
            }
            $v['park_name'] = trim(implode(",",$pk),',');
            if($v['type'] == 1){
                $v['money'] = '--';
            } else if($v['type'] == 2){
                $v['duration'] = '--';
                $v['money'] = re2float($v['money']/100);
            }


        }
        return $this->sendResponse($res, '获取成功');
    }

    /**
     * Store a newly created SellIssues in storage.
     * POST /sellIssues
     *
     * @param CreateSellIssuesAPIRequest $request
     *
     * @return Response
     */
    public function store(CreateSellIssuesAPIRequest $request)
    {
        $input = $request->all();
        $store_res = Store::find($input['store_id']);
        if(empty($store_res->park_ids)){
            return $this->sendError('此商户没有车场！');
        }
        if(empty($store_res->type)){
            return $this->sendError('此商户没有授权类型');
        }
        $exist_sell = SellIssues::where("store_id",$input['store_id'])->where("vpl_number",$input['vpl_number'])->first();
        if($exist_sell){
            return $this->sendError('同商户同车牌已经存在！');
        }
        $parks = explode(",",$store_res->park_ids);
        foreach ($parks as $p) {
            $input['park_code'] = $store_res->park_ids;
            $input['start_time'] = $input['start_time']??$store_res->start_time;
            $input['end_time'] = $input['end_time']??$store_res->end_time;
            $input['duration'] = $input['duration']??$store_res->duration;
            $input['money'] = ($input['money']??0)*100??$store_res->money;
            // 同一车场 车辆 一个时间段里只有一次
            $repeatRes = CarAuth::where([
                "park_code" => $p,
                ["vpl_number",'like',$input['vpl_number'].","],
                ['validbtime', '<=', $input['start_time']],
                ['validetime', '>=', $input['end_time']]
            ])->first();
            if (obj2arr($repeatRes)) {
                return $this->sendError('车辆授权已经存在此授权数据');
            }
            $repeatRes = CarAuth::where([
                "park_code" => $p,
                ["vpl_number",'like',$input['vpl_number'].","],
                ['validbtime', '<', $input['start_time']],
                ['validetime', '>', $input['end_time']],
            ])->first();
            if (obj2arr($repeatRes)) {
                return $this->sendError('车辆授权已经存在此授权数据');
            }
            if(empty($input['start_time'])){
                return $this->sendError('没有开始时间');
            }
            if(empty($input['end_time'])){
                return $this->sendError('没有结束时间');
            }
            $sellIssues = $this->sellIssuesRepository->create($input);

            if ($sellIssues) {
                $data = [];
                $data['park_code'] = $p;
                //  14 => '储时车' ,11 => '储值车',
                if ($sellIssues->type == 1) {
                    $data['type'] = 14;
                } elseif ($sellIssues->type == 2) {
                    $data['type'] = 11;
                }
                $data['share'] = 0;
                $data['share_count'] = 0;
                $data['mobile'] = $sellIssues->phone;
                $data['username'] = $sellIssues->user_name;
                $data['priority'] = 2;
                $data['vpl_number'] = $sellIssues->vpl_number;
                $data['cardno'] = md5(time() . rand(0, 9));
                $data['serial_no'] = $data['cardno'];
                $data['option'] = 'store_add';
                $data['validbtime'] = date("Y-m-d H:i:s", strtotime($sellIssues->start_time));
                $data['validetime'] = date("Y-m-d H:i:s", strtotime($sellIssues->end_time));
                $carAuths = CarAuthLog::create($data);
                $data['validbtime'] = strtotime($sellIssues->start_time);
                $data['validetime'] = strtotime($sellIssues->end_time);
                $data['vpl_number'] = '[["' . $data['vpl_number'] . '",""]]';
                if($sellIssues->type == 2) {
                    $data['recharge'] = '{"pay_type":1,"account":"'.($sellIssues->money).'"}';
                } else {
                    $data['recharge'] = '{"pay_type":2,"account":"'.($input['duration']*3600).'"}';
                }
                // 查看返回状态
                $this->log('开始传递 CAR data');
                $this->log('参数数据:' . json_encode($data));
                $res = $this->sendAuthData($data);
                $this->log('返回参数：'.json_encode($res));
                if ($res['code'] == 0) {
                    $this->sellIssuesRepository->update(['status' => 2, 'cardno' => $data['cardno'], 'serial_no' => $data['serial_no']], $sellIssues->id);
                } else {
                    $this->sellIssuesRepository->update(['status' => 1, 'cardno' => $data['cardno'], 'serial_no' => $data['serial_no']], $sellIssues->id);
                }
            }
        }

        return $this->sendResponse($sellIssues->toArray(), '操作成功');
    }

    /**
     * Display the specified SellIssues.
     * GET|HEAD /sellIssues/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var SellIssues $sellIssues */
        $sellIssues = $this->sellIssuesRepository->findWithoutFail($id);

        if (empty($sellIssues)) {
            return $this->sendError('数据不存在');
        }
        $sellIssues->money = re2float($sellIssues->money/100);
        return $this->sendResponse($sellIssues->toArray(), '获取成功');
    }

    /**
     * Update the specified SellIssues in storage.
     * PUT/PATCH /sellIssues/{id}
     *
     * @param  int $id
     * @param UpdateSellIssuesAPIRequest $request
     *
     * @return Response
     */
    public function update($id, UpdateSellIssuesAPIRequest $request)
    {
        $input = $request->all();
        $store_res = Store::find($input['store_id']);
        /** @var SellIssues $sellIssues */
        $sellIssues = $this->sellIssuesRepository->findWithoutFail($id);

        if (empty($sellIssues)) {
            return $this->sendError('数据不存在');
        }
        $input['start_time'] = $input['start_time']??$store_res->start_time;
        $input['end_time'] = $input['end_time']??$store_res->end_time;
        $input['duration'] = $input['duration']??(strtotime($store_res->end_time)-strtotime($store_res->start_time));
        $input['money'] = $input['money']??$store_res->money;

        $sellIssues = $this->sellIssuesRepository->update($input, $id);
        if($sellIssues){
            $parks = explode(",",$sellIssues->park_code);
            foreach ($parks as $p) {
                $data = [];
                $data['park_code'] = $p;
                //  14 => '储时车' ,11 => '储值车',
                if($sellIssues->type == 1){
                    $data['type'] = 14;
                } elseif($sellIssues->type == 1){
                    $data['type'] = 11;
                }
                $data['share'] = 0;
                $data['share_count'] = 0;
                $data['mobile'] = $sellIssues->phone;
                $data['username'] = $sellIssues->user_name;
                $data['priority'] = 2;
                $data['vpl_number'] = $sellIssues->vpl_number;
                $data['cardno'] = md5(time().rand(0,9));
                $data['serial_no'] = md5(time().rand(0,9));
                $data['validbtime'] = date("Y-m-d H:i:s",strtotime($sellIssues->start_time));
                $data['validetime'] = date("Y-m-d H:i:s",strtotime($sellIssues->end_time));
                $data['option'] = 'store_edit';
                $carAuthlogs = CarAuthLog::create($data);
                unset($data['park_code']);
                $tmp['park_code'] = $p;
                $tmp['cardno'] = $sellIssues->cardno;
                $tmp['serial_no'] = $sellIssues->serial_no;
                $tmp['edit_map'] = json_encode([
                    'share_tol'=>0,
                    'holder_name'=>$sellIssues->username,
                    'validity_start'=>strtotime($input['start_time']),
                    'validity_end'=>strtotime($input['end_time']),
                    'is_share'=>0,
                    'phone'=>$sellIssues->phone,
                    'email'=>'',
                    'plate_list'=>'[["' . $data['vpl_number'] . '",""]]',
                ]);
                $tmp['operator'] = $sellIssues->username;
                $tmp['edit_time'] = time();
                // 查看返回状态
                $this->log('开始传递 CAR data');
                $this->log('参数数据:'.json_encode($tmp));
                $res = $this->editAuthData($tmp);
                $this->log('返回参数：'.($res));
                if($res['code'] == 0){
                    $this->sellIssuesRepository->update(['status'=>2],$id);
                } else {
                    if($carAuthlogs) {
                        $this->sellIssuesRepository->update(['status' => 1], $id);
                    }
                }
            }
        }
        return $this->sendResponse($sellIssues->toArray(), '操作成功');
    }

    /**
     * Remove the specified SellIssues from storage.
     * DELETE /sellIssues/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        /** @var SellIssues $sellIssues */
        $sellIssues = $this->sellIssuesRepository->findWithoutFail($id);
        if (empty($sellIssues)) {
            return $this->sendError('数据不存在');
        }
        if($sellIssues->status != 1) {
            $parks = explode(",", $sellIssues->park_code);
            foreach ($parks as $p) {
                $data = [];
                $data['park_code'] = $p;
                //  14 => '储时车' ,11 => '储值车',
                if ($sellIssues->type == 1) {
                    $data['type'] = 14;
                } elseif ($sellIssues->type == 2) {
                    $data['type'] = 11;
                }
                $data['share'] = 0;
                $data['share_count'] = 0;
                $data['mobile'] = $sellIssues->phone;
                $data['username'] = $sellIssues->user_name;
                $data['priority'] = 2;
                $data['vpl_number'] = $sellIssues->vpl_number;
                $data['cardno'] = $sellIssues->cardno;
                $data['serial_no'] = $sellIssues->serial_no;
                $data['validbtime'] = date("Y-m-d H:i:s", strtotime($sellIssues->start_time));
                $data['validetime'] = date("Y-m-d H:i:s", strtotime($sellIssues->end_time));
                $data['option'] = 'store_delete';
                $carAuthlogs = CarAuthLog::create($data);
                $res = curl_post(config('custom.car_auth_api_url') . "/auth_delete?src=airport", [
                    'serial_no' => $sellIssues->cardno,
                    'cardno' => $sellIssues->serial_no,
                    'park_code' => $p
                ]);
            }
            $this->log('返回参数：'.($res));
            $res = \GuzzleHttp\json_decode($res, true);
            if ($res['code'] == 0) {
                $sellIssues->delete();
                return $this->sendResponse($id, '正在删除授权中.....');
            }
        } else {
            $sellIssues->delete();
        }
        return $this->sendResponse($id, '下发授权删除失败');
    }

    /**
     * 批量下发车辆授权
     *
     * @param Request $request
     */
    public function massAuth(Request $request){
        $filePath = storage_path().'/app/uploads/'.$request->input('file');
        if(!file_exists($filePath)){
            return $this->sendError('文件不存在');
        }
        $store_res = Store::find($request->input('store_id'));
        if(empty($store_res->type)){
            return $this->sendError('此商户授权不存在');
        }
        if(empty($store_res->start_time)){
            return $this->sendError('此商户授权不开始时间');
        }
        if(empty($store_res->end_time)){
            return $this->sendError('此商户授权不结束时间');
        }
        Excel::load($filePath, function($reader) use($filePath,$store_res){
            $reader = $reader->getSheet(0);
            $res = $reader->toArray();
            // 0 车牌号  1共享车位 2 授权类型  3 起始时间 4 结束日期 5 电话 6 所属机构
            unset($res[0]); // 注销文件首行
            if(count($res)>200){
                $r = [
                    'success'=>false,
                    'data'=>[],
                    'message'=>'授权数目超过200，请分批授权！！',
                ];
                exit(json_encode($r));
            }
            $parks = explode(",",$store_res->park_ids);
            $carAuths = [];
            foreach ($res as $re) {
                if(empty($re[1])) continue;
                $exist_sell = SellIssues::where("store_id",$store_res->id)->where("vpl_number",$re[1])->first();
                if($exist_sell){
                    continue;
                }
                foreach ($parks as $p) {
                    //插入授权下发表
                    $insert = [];
                    $insert['user_name'] = $re[0];
                    $insert['vpl_number'] = $re[1];
                    if ($store_res->type == 1) {
                        $insert['type'] = 14;
                        $insert['money'] = $re[2]*3600;
                    } elseif ($store_res->type == 2) {
                        $insert['type'] = 11;
                        $insert['money'] = $re[2]*100;
                    }
                    $insert['store_id'] = $store_res->id;
                    $insert['park_code'] = $p;
                    $insert['status'] = 1;
                    $insert['phone'] = $re[4];
                    $insert['start_time'] = $store_res->start_time;
                    $insert['end_time'] = $store_res->end_time;
                    $insert['duration'] = $re[2];
                    $insert['cardno'] = md5(time().rand(0,9));
                    $insert['serial_no'] = md5(time().rand(0,9));
                    // 同一车场 车辆 一个时间段里只有一次
                    $repeatRes = CarAuth::where([
                        "park_code" => $p,
                        ["vpl_number",'like',$re[1].","],
                        ['validbtime', '<=', $insert['start_time']],
                        ['validetime', '>=', $insert['end_time']]
                    ])->first();
                    if (obj2arr($repeatRes)) {
                        return $this->sendError('车辆授权已经存在此授权数据');
                    }
                    $repeatRes = CarAuth::where([
                        "park_code" => $p,
                        ["vpl_number",'like',$re[1].","],
                        ['validbtime', '<', $insert['start_time']],
                        ['validetime', '>', $insert['end_time']],
                    ])->first();
                    $selle_res = SellIssues::create($insert);
                    // 同一车场 车辆 一个时间段里只有一次
                    $data = [];
                    unset($data['park_code']);
                    $data['park_code'] = $p;
                    if ($store_res->type == 1) {
                        $data['type'] = 14;
                    } elseif ($store_res->type == 2) {
                        $data['type'] = 11;
                    }
                    $data['share'] = 0;
                    $data['share_count'] = 0;
                    $data['mobile'] = $re['6'];
                    $data['username'] = $re[0];
                    $data['priority'] = 2;
                    $data['vpl_number'] = $re[1];
                    $data['cardno'] = $insert['cardno'];
                    $data['serial_no'] = $insert['serial_no'];
                    $data['option'] = 'store_add';
                    $data['validbtime'] = date("Y-m-d H:i:s",strtotime($re[4]));
                    $data['validetime'] = date("Y-m-d H:i:s",strtotime($re[5]));
                    $carAuths = CarAuthLog::create($data);
                    $data['validbtime'] = strtotime($re[4]);
                    $data['validetime'] = strtotime($re[5]);

                    if($carAuths) {
                        $data['vpl_number'] = '[["' . $re[1] . '",""]]';
                        if($store_res->type == 2) {
                            $tmp['recharge'] = '[["pay_type":1,"account":"'.($re[2]*100).'"]]';
                        } else {
                            $tmp['recharge'] = '[["pay_type":2,"account":"'.($re[2]*3600).'"]]';
                        }
                        // 查看返回状态
                        $this->log('开始传递 CAR data');
                        $this->log('参数数据:'.json_encode($data));
                        $res = $this->sendAuthData($data);
                        $this->log('返回参数：'.json_encode($res));
                        if($res['code'] == 0){
                            $this->sellIssuesRepository->update(['status'=>2],$selle_res->id);
                        } else {
                            if($carAuths) {
                                $this->sellIssuesRepository->update(['status' => 1], $selle_res->id);
                            }
                        }
                    }
                }
            }
            if(file_exists($filePath)) unlink($filePath);
            $r = [
                'success'=>true,
                'data'=>isset($carAuths)?$carAuths->toArray():[],
                'message'=>'正在下发授权中......',
            ];
            exit(json_encode($r));
        });

        return $this->sendError('无效文件');
    }


    /**
     * 批量下发车辆授权
     *
     * @param Request $request
     */
    public function massFile(Request $request){
        $file = $request->file('file');
        // 文件是否上传成功
        if ($file->isValid()) {
            // 获取文件相关信息
            $originalName = $file->getClientOriginalName(); // 文件原名
            $ext = $file->getClientOriginalExtension();     // 扩展名
            $realPath = $file->getRealPath();   //临时文件的绝对路径
            $type = $file->getClientMimeType();     // image/jpeg
            // 上传文件
            $filename =  time().'.' . $ext;
            $filePath = storage_path().'/app/uploads/'.$filename;
            // 使用我们新建的uploads本地存储空间（目录）
            //这里的uploads是配置文件的名称
            $bool = Storage::disk('uploads')->put($filename, fopen($request->file('file')->getRealPath(), 'r'));
            if(!file_exists($filePath)){
                return $this->sendError('上传失败');
            }
            if($bool){
                $auth_type = config('custom.auth_type');
                $auth_type = array_flip($auth_type);
                Excel::load($filePath, function($reader) use($filePath,$auth_type){
                    $reader = $reader->getSheet(0);
                    $res = $reader->toArray();
                    // 0 车牌号  1共享车位 2 授权类型  3 起始时间 4 结束日期 5 电话 6 所属机构
                    unset($res[0]); // 注销文件首行
                    foreach ($res as $re) {
                        if(empty($re[1])) continue;
                        //判断时间格式
                        if(strtotime($re['4']) == '' || strtotime($re['5']) == ''){
                            $r = [
                                'success'=>false,
                                'data'=>[],
                                'message'=>'文件授权时间格式有问题！',
                            ];
                            exit(json_encode($r));
                        }
                    }
                });
                return $this->sendResponse($filename, '上传成功');
            }
            return $this->sendError('上传失败');
        }
        return $this->sendError('无效文件');
    }
}
